package com.cll.prototype.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 描述信息:
 * 自定义黑名单过滤器
 * gateway是基于WebFlux暴漏接口的
 * @author CLL
 * @version 1.0
 * @date 2020/11/9 9:12
 */
@Component
public class BlackListFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(BlackListFilter.class);

    /**
     * 模拟黑名单（实际可以去数据库或者redis中查询）
     */
    private static List<String> blackList = new ArrayList<>();

    static {
        logger.info("===>>> init black ip list...");
        // 模拟本机地址
        blackList.add("0:0:0:0:0:0:0:1");
    }


    /**
     * 过滤器逻辑处理
     * @param exchange 封装的请求和响应对象。进行数据交换
     * @param chain gateway的过滤器链路
     * @return  过滤器返回结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("===>>> black list filter ");
        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        String clientIp = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
        // 拿着clientIp去黑名单中查询，存在的话就决绝访问
        if(blackList.contains(clientIp)) {
            // 拒绝访问，返回状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            logger.error("****** IP:{}在黑名单中，将被拒绝访问！", clientIp);
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    /**
     * 当前过滤器在过滤器链路中的顺序
     * @return  过滤器级别。返回值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}